/**
 * 
 */
package com.local.guava.listenablefuture;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

/**
 * @author Administrator
 *
 */
public class ListenableFutureDemo {


	public void for_example(){
		ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
		final ListenableFuture<Integer> listenableFuture = executorService.submit(new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				System.out.println("程序执行..");
				TimeUnit.SECONDS.sleep(1);
				return 7;
			}
		});

		
		//通过ListenableFuture的addListener方法
		listenableFuture.addListener(new Runnable() {
			@Override
			public void run() {
				try {
					System.out.println("返回结果: " + listenableFuture.get());
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
			}
		}, executorService);
	}

	
	public void for_example_other(){
		ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
		final ListenableFuture<Integer> listenableFuture = executorService.submit(new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				System.out.println("call execute..");
				TimeUnit.SECONDS.sleep(1);
				return 7;
			}
		});

		//通过Futures的静态方法addCallback给ListenableFuture添加回调函数()
		Futures.addCallback(listenableFuture, new FutureCallback<Integer>() {
            @Override
            public void onSuccess(Integer result) {
                System.out.println("get listenable future's result with callback " + result);
            }

            @Override
            public void onFailure(Throwable t) {
                t.printStackTrace();
            }
        });
	}

	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
       new ListenableFutureDemo().for_example();
       new ListenableFutureDemo().for_example_other();
	}

}
